<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
            贪心法：首先计算每个站点的剩余油量。
            i从0开始统计剩余油量的和curSum，一旦curSum<0说明当前起点i不能作为起点位置。必须从i+1重新开始
            计算curSum。
            
            */
            var canCompleteCircuit = function (gas, cost) {
                let curSum = 0
                let start = 0
                let totalSum = 0
                for (let i = 0; i < gas.length; i++) {
                    let rest = gas[i] - cost[i]
                    curSum += rest
                    totalSum += rest
                    if (curSum < 0) {
                        //从头开始
                        start = i + 1
                        curSum = 0
                    }
                }
                //如果最后总剩余流量小于0，说明无解，不然一定有解
                if (totalSum < 0) return -1
                return start
            }
        </script>
    </body>
</html>
